<?php


namespace StarCloud\Library\Sdk;

use Phalcon\Di;
use StarCloud\Library\HttpCurl;

class KsSass
{
    use HttpCurl;

    private $appId = "ks686798946421493355";
    private $secret = "DS-iVE7qyYa7zX8DtgQa1Q";
    private $callBack = "https://api.doumvip.com/api/ks/authorizationCallback";
    private $component_access_token = "";
    private $authorizer_access_token = "";

    private $msgKey = "fengshuangfengshuangfengshuangfengshuang521";

    public function __construct()
    {
        $this->cacheClass = Di::getDefault()->get('redis');
    }

    public function findAuthCode($appId)
    {
        $url = "https://open.kuaishou.com/mp/tp/oauth/re_authorization_code?";
        $query = [
            'component_app_id' => $this->appId,
            'component_access_token' => $this->getComponentAccessToken(),
            'authorized_app_id' => $appId,
        ];
        $result = $this->http_get($url . http_build_query($query));

        $json = json_decode($result, true);
        return $json['authorizationCode'];
    }


    public function get_pre_auth_code()
    {
        $query = [
            'component_app_id' => $this->appId,
            'component_access_token' => $this->getComponentAccessToken(),
        ];
        $result = $this->http_get("https://open.kuaishou.com/mp/tp/oauth/pre_auth_code?" . http_build_query($query));
        Di::getDefault()->get('logger')->info("ks_sass_get_pre_auth_code" . "req:" . json_encode($query));
        Di::getDefault()->get('logger')->info("ks_sass_get_pre_auth_code" . "res:" . $result);

        $json = json_decode($result, true);

        return $json['preAuthCode'];
    }

    public function authorizer_refresh_token($appId)
    {
        $url = "https://open.kuaishou.com/mp/tp/oauth/authorizer_refresh_token?";

        $cacheName = "ks_authorizer_app_id" . $appId;
        $json = $this->cacheClass->get($cacheName);
        $json = json_decode($json, true);
        $query = [
            'component_app_id' => $this->appId,
            'component_access_token' => $this->getComponentAccessToken(),
            'authorizer_refresh_token' => $json['authorizerRefreshToken'],
        ];

        $result = $this->http_get($url . http_build_query($query));

        $newjson = json_decode($result, true);
        var_dump($newjson);
        if (isset($newjson['result']) && $json['result'] == 1) {
            $this->authorizer_access_token = $newjson['authorizerAccessToken'];
            $json['authorizerAccessToken'] = $newjson['authorizerAccessToken'];
            $json['authorizerRefreshToken'] = $newjson['authorizerRefreshToken'];
            $this->setAuthorizerCache($json);
            $this->authorizer_access_token;
        }
        return false;
    }

    public function getRedirectUrl($callBack = "")
    {
        if (empty($callBack)) {
            $callBack = $this->callBack;
        }
        $preAuthCode = $this->get_pre_auth_code();
        $callBack = urlencode($callBack);
        return "https://mp-saas.kuaishou.com/oauth/authorization?component_app_id={$this->appId}&pre_auth_code={$preAuthCode}&redirect_uri={$callBack}";
    }

    public function authorizer_access_token($params)
    {
        $code = $params['authorization_code'];
        $query = [
            'component_app_id' => $this->appId,
            'component_access_token' => $this->getComponentAccessToken(),
            'authorization_code' => $code,
        ];
        $result = $this->http_get("https://open.kuaishou.com/mp/tp/oauth/authorizer_access_token?". http_build_query($query));

        Di::getDefault()->get('logger')->info("ks_sass_get_pre_auth_code" . "req:" . json_encode($query));
        Di::getDefault()->get('logger')->info("ks_sass_get_pre_auth_code" . "res:" . $result);

        $json = json_decode($result, true);

        if (isset($json['result']) && $json['result'] == 1) {
            $this->authorizer_access_token = $json['authorizerAccessToken'];
            $this->setAuthorizerCache($json);
            return $this->authorizer_access_token;
        }
        return false;
    }

    private function setAuthorizerCache($json)
    {
        $cacheName = "ks_authorizer_app_id" . $json['authorizerAppId'];
        $cacheNameToken = "ks_authorizer_app_id_token" . $json['authorizerAppId'];
        Di::getDefault()->get("logger")->info($cacheNameToken . " :" . $json['authorizerAccessToken']);
        $this->setCache($cacheName, json_encode($json), 0);
        $this->setCache($cacheNameToken, $json['authorizerAccessToken'], 7000);
    }

    public function get_authorizer_access_token($authorizerAppId)
    {
        $cacheNameToken = "ks_authorizer_app_id_token" . $authorizerAppId;
        return $this->getCache($cacheNameToken);
    }

    public function getAuthPlcMembers($authorizerAppId = "", $page = 1, $size = 50)
    {
        $url = "https://open.kuaishou.com/openapi/mp/auth/plc/members?";
        $query = [
            'component_app_id' => $this->appId,
            'authorizer_access_token' => $this->get_authorizer_access_token($authorizerAppId),
            'pageNum' => $page,
            'pageSize' => $size,
        ];
        $times = 1;

        while ($times <= 20) {
            $result = $this->http_get($url . http_build_query($query));
            $json = json_decode($result, true);
            var_dump($json);
            if (isset($json['data'])) {
                return $json['data'];
            } else {
                $times++;
                sleep(2);
            }
        }

        return false;
    }

    public function getComponentAccessToken()
    {
        $authname = 'ks_sass_access_token'.$this->appId;
        $rs = $this->getCache($authname);
        $this->component_access_token = $rs;
        return $rs;
    }

    public function checkComponentAuth($ticket)
    {
        $authname = 'ks_sass_access_token'.$this->appId;

        if ($rs = $this->getCache($authname)) {
            $this->component_access_token = $rs;
            return $rs;
        }

        $result = $this->http_get("https://open.kuaishou.com/mp/tp/oauth/access_token?" . http_build_query([
            'component_app_id' => $this->appId,
            'component_app_secret' => $this->secret,
            'component_verify_ticket' => $ticket,
        ]));
        Di::getDefault()->get('logger')->info("ks_sass_component_access_token" . $result);
        $json = json_decode($result, true);
        if (isset($json['result']) && $json['result'] == 1) {
            $this->component_access_token = $json['componentAccessToken'];
            $this->setCache($authname, $json['componentAccessToken'], 7000);
            $this->component_access_token;
        }

        return false;
    }

    public function start_push_ticket()
    {
        $url = "https://open.kuaishou.com/mp/tp/oauth/start_push_ticket?";

        $data = $this->http_get($url . http_build_query([
                "time" => time(),
                'component_app_id' => $this->appId,
                'component_app_secret' => $this->secret
            ]));

        $json = json_decode($data, true);

        if (isset($json['result']) && $json['result'] == 1) {
            return true;
        }

        return false;
    }

    public function encrypt($data)
    {
        $msgKey = base64_decode($this->msgKey);
        $iv = substr($msgKey, 0, 16);
        $encrypted = openssl_encrypt($data, 'AES-256-CBC', substr($msgKey, 0, 32), OPENSSL_RAW_DATA, $iv);
        return base64_encode($encrypted); // 将加密数据和初始化向量进行编码
    }


    public function decryptedMsg($msg = "") {

        $msgKey = base64_decode($this->msgKey);
        $iv = substr($msgKey, 0, 16);
        $decrypted = openssl_decrypt($msg, 'AES-256-CBC', substr($msgKey, 0, 32), OPENSSL_ZERO_PADDING, $iv);
        return $decrypted;
    }
}
